﻿using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.RBAC;
using MediatR;
using System.Transactions;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.RBAC
{

    /// <summary>
    /// 添加用户信息命令处理
    /// </summary>
    public class AddUserCommandHandlter : IRequestHandler<AddUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRep;
        private readonly IBaseRepository<UserRoleModel> userRoleRep;

        public AddUserCommandHandlter(IBaseRepository<UserModel> userRep, IBaseRepository<UserRoleModel> userRoleRep)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
        }


        public async Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {

            var username = userRep.GetAll().FirstOrDefault(x => x.UserName == request.UserName);

            if (username != null)
            {
                return new ApiResult<int>()
                {
                    code = ResultEnumCode.fails,
                    data = 0,
                    message = "用户名已存在"

                };
            }

            //分布式事务
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {

                try
                {
                    //添加用户信息
                    UserModel user = new UserModel()
                    {
                        CreateTime = DateTime.Now,
                        IsDeleted = false,
                        IsState = true,
                        Password = request.Password,
                        UserName = request.UserName,
                        UpdateTime = DateTime.Now,

                    };

                    await userRep.AddAsync(user);

                    //添加用户角色信息

                    foreach (var RoleId in request.RoleIds)
                    {

                        UserRoleModel role = new UserRoleModel()
                        {
                            RoleId = RoleId,
                            UpdateTime = DateTime.Now,
                            IsDeleted = false,
                            IsState = true,
                            CreateTime = DateTime.Now,
                            UserId = user.ID,
                        };

                        await userRoleRep.AddAsync(role);
                    }


                    //提交事务
                    tran.Complete();

                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Dispose();
                    throw;
                }


            }

            return new ApiResult<int>()
            {
                code = ResultEnumCode.Ok,
                data = 1,
                message = "新增用户成功"


            };
        }
    }
}
